package com.liver_cloud.service.patient;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liver_cloud.dao.mybatis.DaoSupport;
import com.liver_cloud.util.Consts;
import com.liver_cloud.util.ImageUpLoader;
import com.liver_cloud.util.PageData;

@Service
public class PatientService {
	
	@Resource(name="daoSupport")
	private DaoSupport dao;

	public PageData getPatientMessage(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//根据患者的userId去message表查询患者参与的对话
		PageData result = new PageData();
		result.put("changed", false);
		result.put("list", "");
		pd.put("transferSucess", "0");
		List<PageData> messageList = 
				(List<PageData>) dao.findForList("PatientMapper.getPatientMessage", pd);
		//患者未发起过对话
		if(messageList == null || messageList.size()==0){
			return result;
		}
		result.put("list", messageList);
		//添加信息个数
		result.put("messageNum", messageList.size());
		
		//遍历集合，添加信息
		for(int i=0;i<messageList.size();i++){
			//患者message是否修改过
			String changed = messageList.get(i).get("changed").toString();
			if("1".equals(changed)){
				result.put("changed", true);
				//对每条信息添加是否是新消息
				messageList.get(i).put("changed", true);	
			}			
			String ifTransfer = messageList.get(i).get("ifTransfer").toString();
			if("1".equals(ifTransfer)){			
				messageList.get(i).put("ifTransfer", true);			
			}else{
				messageList.get(i).put("ifTransfer", false);
			}
			
			//根据doctorId在doctor_info表查询医生信息
			String doctorId = messageList.get(i).get("doctorId").toString();
			//根据messageId查询是否有解决方案
			String messageId = messageList.get(i).get("messageId").toString();
			/*pd.put("doctorId", doctorId);
			PageData solution = 
					(PageData) dao.findForObject("PatientMapper.getSolution", pd);*/
			PageData solution = 
					(PageData) dao.findForObject("PatientMapper.getSolutionByMessageId", messageId);
			if(solution != null){
				messageList.get(i).put("solutionId", solution.get("solutionId").toString());
			}else{
				messageList.get(i).put("solutionId", "");
			}			
			String doctorName =
					(String) dao.findForObject("DoctorMapper.getDoctorInfoByDoctorId", doctorId);
			//user表查询头像,根据doctorId获取在平台中的Id
			String myDoctorId = doctorId;
			String platformId = 
					(String) dao.findForObject("DoctorMapper.getPlatformId", myDoctorId);
			String imageUrl =
					(String) dao.findForObject("DoctorMapper.getDoctorImageUrl", platformId);		
			String questionId = "";
			String questionContent = "";
			String messageInfoId = "";
			String templateContent = "";
			messageList.get(i).put("ifReply", false);
			//根据messageId查询最近的一次问答
			PageData question = 
					(PageData) dao.findForObject("DoctorMapper.getLastQuestion", messageId);
			if(question != null ){
				questionId = question.get("questionId").toString();
				//根据questionId查询reply表，判断该医生问题是否被患者回复了
				PageData reply = 
						(PageData) dao.findForObject("DoctorMapper.findReply", questionId);
				if(reply != null){
					messageList.get(i).put("ifReply", true);
				}
				if(question.get("questionContent") != null){
					questionContent = question.get("questionContent").toString();					
				}
				messageInfoId = question.get("messageInfoId").toString();
				//根据messageInfoId在messInfo表查询患者提问的问题
				templateContent = 
						(String) dao.findForObject("DoctorMapper.getTemplateContent", messageInfoId);				
			}else{
				//表示没有医生进行过回答，则根据messageId获取templateContent
				templateContent =
						(String) dao.findForObject("DoctorMapper.getTempContent", messageId);				
			}
			messageList.get(i).put("doctorName", doctorName);
			messageList.get(i).put("imageUrl", imageUrl);
			messageList.get(i).put("templateContent", templateContent);
			messageList.get(i).put("questionContent", questionContent);
			messageList.get(i).put("questionId", questionId);			
		}
		
		return result;
	}

	public PageData getQuestionDetail(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		//根据messageId获取医生Id
		String doctorId = 
				(String) dao.findForObject("PatientMapper.getDoctorId", pd);
		//根据doctorId获取医生姓名，医院，职务及头像url
		//user表查询头像
		String myDoctorId = doctorId;
		String platformId = 
				(String) dao.findForObject("DoctorMapper.getPlatformId", myDoctorId);
		String imageUrl =
				(String) dao.findForObject("DoctorMapper.getDoctorImageUrl", platformId);	
		PageData doctorInfo = 
				(PageData) dao.findForObject("DoctorMapper.getDoctorById", doctorId);
		String doctorName = doctorInfo.getString("doctorName");
		String hospital = doctorInfo.getString("hospital");
		//根据doctorId获取医生职务
		String professionName = 
				(String) dao.findForObject("DoctorMapper.getProfessionName", doctorId);
		//根据messageId查询messageInfo列表
		List<PageData> messageInfoList = 
				(List<PageData>) dao.findForList("DoctorMapper.getMessageInfoList", pd);
		//遍历集合
		for(int i=0;i<messageInfoList.size();i++){
			
			messageInfoList.get(i).put("ifDetail", false);
			messageInfoList.get(i).put("ifCustomDefined", false);
			
			//判断是否已经转诊
			String ifTransfer =messageInfoList.get(i).get("templateTransfer").toString(); 
			if("1".equals(ifTransfer)){
				messageInfoList.get(i).put("ifTransfer", true);
			}else{
				messageInfoList.get(i).put("ifTransfer", false);
			}			
			//根据templateId拿到template
			String templateId = messageInfoList.get(i).get("templateId").toString();
			String template = 
					(String) dao.findForObject("DoctorMapper.getTemplateById", templateId);
			messageInfoList.get(i).put("template", template);
			String messageInfoId = messageInfoList.get(i).get("messageInfoId").toString();
			//获取该模块对应的问答列表，并按时间降序排列
			List<PageData> questionList = 
					(List<PageData>) dao.findForList("DoctorMapper.getQuestionList", messageInfoId);
			//遍历问答集合，根据questionId查询reply信息，并插入到问答列表中
			for(int j=0;j<questionList.size();j++){
				String questionId = questionList.get(j).get("questionId").toString();
				PageData reply = 
						(PageData) dao.findForObject("DoctorMapper.getReply", questionId);
				questionList.get(j).put("questioner", "doctor");
				
				if(reply == null){
					continue;
				}else{
					reply.put("questioner", "patient");
					//添加到问答列表
					questionList.add(j+1, reply);
					j++;
				}
												
			}
			//集合倒叙
			List<PageData> resultList = new ArrayList<PageData>();
			if(questionList.size()>0){
				for(int j=questionList.size()-1;j>=0;j--){
					resultList.add(questionList.get(j));
				}				
			}			
			messageInfoList.get(i).put("questionList", resultList);
			
		}
		result.put("doctorName", doctorName);
		result.put("hospital", hospital);
		result.put("professionName", professionName);
		result.put("imageUrl", imageUrl);
		PageData temp1 = null;
		PageData temp2 = null;
		int tem1 = 0;
		int tem2 = 0;
		for(int i=0;i<messageInfoList.size();i++){
			String templateId = messageInfoList.get(i).get("templateId")
					.toString();
			if("14".equals(templateId)){
				temp1 = messageInfoList.get(i);
				tem1 = i;
			}
		}
		if(temp1 != null){
			messageInfoList.add(0, temp1);
			messageInfoList.get(0).put("ifDetail", true);
			messageInfoList.remove(tem1+1);
		}
		for(int i=0;i<messageInfoList.size();i++){
			String templateId = messageInfoList.get(i).get("templateId")
					.toString();
			if("15".equals(templateId)){
				temp2 = messageInfoList.get(i);
				tem2 = i;
			}
		}
		if(temp2 != null){
			messageInfoList.add(messageInfoList.size(), temp2);
			messageInfoList.get(messageInfoList.size()-1).put("ifCustomDefined", true);
			messageInfoList.remove(temp2);
		}
		
		result.put("list", messageInfoList);
		result.put("messageId", pd.getString("messageId"));
		//将本messageId对应的患者消息变动改为0
		pd.put("patientChanged", "0");
		dao.update("PatientMapper.changePatientMessageState", pd);
		return result;
	}

	
	public PageData saveReplyContent(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//回复时间
		Date createTime = new Date();
		pd.put("createTime", createTime);
		//查询是否已经回复了
		PageData replyInfo = 
				(PageData) dao.findForObject("PatientMapper.getReply", pd);
		if(replyInfo != null){
			return replyInfo;
		}
		dao.save("PatientMapper.saveReplyContent", pd);
		//将回话列表中医生的消息变动改为1,患者的消息变动改为0
		pd.put("doctorChanged", "1");
		pd.put("patientChanged", "0");
		dao.update("PatientMapper.doctorMessageChanged", pd);
		return null;
	}

	public PageData getDoctorSolution(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData solutionInfo = 
				(PageData) dao.findForObject("PatientMapper.getDoctorSolution", pd);
		//根据messageId将患者端动态改为0
		dao.update("PatientMapper.updateStatusChanged", solutionInfo);
		
		return (PageData) dao.findForObject("PatientMapper.getDoctorSolution", pd);
	}

	public List<PageData> getRecommendModle(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//根据患者Id查询患者病例填写的症状
		return (List<PageData>) dao.findForList("PatientMapper.getRecommendModle", pd);
	}

	public List<PageData> getRecommendDoctorList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//根据患者症状，省份，区查询医生	
		String diagnosis = pd.getString("diagnosisType");
		ArrayList<String> diagnosisList = new ArrayList<String>();
		if(diagnosis == null){
			diagnosisList.add("1");
			diagnosisList.add("2");
			diagnosisList.add("3");	
		}else{
			String[] list = diagnosis.split(",");
			if(list == null||list[0].equals("")){
				//默认推荐脂肪肝
				diagnosisList.add("1");
				diagnosisList.add("2");		
			}else{
				for(int i=0;i<list.length;i++){
					if(!list[i].equals("")){						
						diagnosisList.add(list[i]);
					}
				}						
			}			
		}
		pd.put("diagnosisList", diagnosisList);	
		List<PageData> doctorList = 
				(List<PageData>) dao.findForList("PatientMapper.getRecommendDoctorList", pd);
		//填充数据
		return fillDoctorListData(doctorList);
	}

	public List<PageData> getDoctorList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		List<PageData> doctorList = 
				(List<PageData>) dao.findForList("DoctorMapper.getDoctorList", pd);
		//添加每个医生的详细信息					
				return fillDoctorListData(doctorList);
	}

	private List<PageData> fillDoctorListData(List<PageData> doctorList) throws Exception {
		// TODO Auto-generated method stub
		for(int i=0;i<doctorList.size();i++){
			String myDoctorId = doctorList.get(i).get("doctorId").toString();
			String regionId = doctorList.get(i).get("region").toString();
			String region = 
					(String) dao.findForObject("DoctorMapper.getRegionByRegionId", regionId);
			doctorList.get(i).put("region", region);
			String provinceId = doctorList.get(i).get("province").toString();
			String province = 
					(String) dao.findForObject("DoctorMapper.getProvinceByProvinceId", provinceId);
			doctorList.get(i).put("province", province);
			//根据doctorId查询平台里面的userId
			String platformId = 
					(String) dao.findForObject("DoctorMapper.getPlatformId", myDoctorId);
			
			//user表查询头像
			String imageUrl =
					(String) dao.findForObject("DoctorMapper.getDoctorImageUrl", platformId);
			//根据departmentId查询科室
			String departmentName = "";
			if( doctorList.get(i).get("departmentId") != null){
				String departmentId = doctorList.get(i).get("departmentId").toString();
				departmentName = 
						(String) dao.findForObject("DoctorMapper.getDepartmentName", departmentId);				
			}
			//根据professionId查询职称
			String professionName = "";
			if(doctorList.get(i).get("professionId") != null){
				String professionId = doctorList.get(i).get("professionId").toString();
				professionName = 
						(String) dao.findForObject("DoctorMapper.getDoctorProfessionName", professionId);				
			}
			doctorList.get(i).put("professionName", professionName);			
			doctorList.get(i).put("imageUrl", imageUrl);
			doctorList.get(i).put("departmentName", departmentName);			
		}	
		return doctorList;
	}

	public PageData getQuestionTemplateList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//根据doctorId查询医生详情
		PageData doctorInfo = 
				(PageData) dao.findForObject("DoctorMapper.getDoctorInfo", pd);
		if(doctorInfo == null){
			return null;
		}
		String doctorId = doctorInfo.get("doctorId").toString();
		
		String regionId = doctorInfo.get("region").toString();
		String region = 
				(String) dao.findForObject("DoctorMapper.getRegionByRegionId", regionId);
		doctorInfo.put("region", region);
		String provinceId = doctorInfo.get("province").toString();
		String province = 
				(String) dao.findForObject("DoctorMapper.getProvinceByProvinceId", provinceId);
		doctorInfo.put("province", province);		
		//user表查询头像
		String myDoctorId = doctorId;
		String platformId = 
				(String) dao.findForObject("DoctorMapper.getPlatformId", myDoctorId);
		String imageUrl =
				(String) dao.findForObject("DoctorMapper.getDoctorImageUrl", platformId);
		//根据professionId查询职称
		String professionName = "";
		if(doctorInfo.get("professionId") != null){
			String professionId =
					doctorInfo.get("professionId").toString();
			professionName =
					(String) dao.findForObject("DoctorMapper.getDoctorProfessionName", professionId);			
		}
		//根据departmentId查询科室
		String departmentName = "";
		if(doctorInfo.get("departmentId") != null){
			String departmentId = doctorInfo.get("departmentId").toString();
			departmentName = 
					(String) dao.findForObject("DoctorMapper.getDepartmentName", departmentId);			
		}
		
		doctorInfo.put("imageUrl", imageUrl);
		doctorInfo.put("departmentName", departmentName);
		doctorInfo.put("professionName", professionName);		
		//获取模板列表
		/*List<PageData> templateList  = 
				(List<PageData>) dao.findForList("PatientMapper.getTemplateList", null);*/
		//遍历集合，修改返回格式
		List<Object> resultList = new ArrayList<Object>();
		
		PageData temp = new PageData();
		temp.put("illDetail", "最近病情描述");
		temp.put("definedQuestion", "自定义问题");
		PageData illDetail = (PageData) dao.findForObject("PatientMapper.findIllDetail", temp);
		PageData definedQuestion = (PageData) dao.findForObject("PatientMapper.getDefinedQuestion", temp);
		
		resultList.add(illDetail);
		List<PageData> templateList  = (List<PageData>) dao.findForList("PatientMapper.getList", temp);
		PageData listTemp = new PageData();
		listTemp.put("myList", templateList);
		listTemp.put("templateContent", "我的问题");
		
		resultList.add(listTemp);
		resultList.add(definedQuestion);
				
		doctorInfo.put("list", resultList);		
		return doctorInfo;
	}

	public void savePatientQuestion(JSONObject obj) throws Exception {
		// TODO Auto-generated method stub
		//message表建立患者和医生的对话信息
		JSONObject list = obj.getJSONObject("param");
		JSONArray dic = list.getJSONArray("templateList");
		String doctorId =  list.getString("doctorId");
		String patientId =  list.getString("patientId");
		//System.out.println(dic+"jsonarray");
		PageData temp = new PageData();
		temp.put("doctorId", doctorId);
		temp.put("patientId", patientId);
		//首先，根据doctorId和patientId建立起医生和患者的对话
		temp.put("createTime", new Date());
		temp.put("doctorChanged", "1");
		//先判断是否已经有对话,同一患者和同一医生可以发起多个对话，此处不再检验
		/*PageData message =  
				(PageData) dao.findForObject("PatientMapper.findMessageByBothId", temp);
		if(message != null){
			return;
		}*/
		//建立会话 
		dao.save("PatientMapper.createMessage", temp);
		//查询刚建立的会话Id,由于同一患者和医生可以建立多次对话，所以查询条件需要加上时间，同时保险期间加上limit 1
		PageData info = 
				(PageData) dao.findForObject("PatientMapper.findMessageByBothId", temp);
		String messageId = info.get("m_id").toString();
		temp.put("messageId", messageId);
		for(int i= 0;i<dic.size();i++){
			JSONObject objTemp = dic.getJSONObject(i);
			if(objTemp.get("templateId") != null && objTemp.get("content") != null ){
				String templateId  = objTemp.get("templateId").toString();
				String content = objTemp.get("content").toString();
				temp.put("templateId", templateId);
				temp.put("content", content);
				dao.save("PatientMapper.savePatientQuestion", temp);				
			}
		}
	}

	public List<PageData> getProfessionNameList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		List<PageData> professionNameList = 
				(List<PageData>) dao.findForList("DoctorMapper.getProfessionNameList", null);
		if("0".equals(pd.getString("ifNeedAll"))){
			return professionNameList;
		}
		PageData temp = new PageData();
		temp.put("professionId", "");
		temp.put("professionName", "全部");
		professionNameList.add(0, temp);
		return professionNameList;
	}

	public List<PageData> getDepartMentList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		List<PageData> departMentList = 
				(List<PageData>) dao.findForList("DoctorMapper.getDepartMentList", null);
		if("0".equals(pd.getString("ifNeedAll"))){
			return departMentList;
		}
		PageData temp = new PageData();
		temp.put("departmentId", "");
		temp.put("departmentName", "全部");
		departMentList.add(0, temp);
		return departMentList;
	}

	public List<PageData> getDiagnosisList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		List<String> necessaryList =  (List<String>) dao.findForList("PatientMapper.getDiagnosisList", pd);
		List<PageData> result = new ArrayList<PageData>();
		for(int i = 0;i<necessaryList.size();i++){
			PageData temp = new PageData();
			temp.put("diagnosisName", necessaryList.get(i));
			temp.put("ifSystem", true);
			result.add(temp);
		}	
		//去重查询
		List<String> patientList = 
				(List<String>) dao.findForList("PatientMapper.getPatientOwnDiagnosisList", pd);
		for(int i=0;i<patientList.size();i++){
			PageData temp = new PageData();
			temp.put("diagnosisName", patientList.get(i));
			temp.put("ifSystem", false);
			result.add(temp);		
		}
		return result;
	}

	public void saveDiagnosisType(PageData pd) throws Exception {
		PageData diagnosis = 
				(PageData) dao.findForObject("PatientMapper.findDiagnosis", pd);
		if(diagnosis != null){
			return;
		}else{
			//添加数据
			dao.save("PatientMapper.addDiagnosis", pd);
			
		}		
		
	}

	public PageData getPatientCasePage(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
				
		//判断该用户是否已经创建过病例
		PageData illnessCase = 
				(PageData) dao.findForObject("PatientMapper.getCase", pd);
		if(illnessCase == null){
			//为该用户创建一个病例
			dao.save("PatientMapper.createCase", pd);
		}	
		//在md_patient_diagnosis表里查询患者添加的病症
		List<PageData> diagnosisList = 
				(List<PageData>) dao.findForList("PatientMapper.getPatientDiagnosisList", pd);
		result.put("diagnosisList", diagnosisList);
		//根据userId查询病症名称及类型
		/*PageData diagnosis = 
				(PageData) dao.findForObject("PatientMapper.getDiagnosis", pd);
		//根据userId查询体重腰围表里面的数据，得到身高，体重，腰围
		if(diagnosis == null){
			//return null;
			diagnosis = new PageData();
			diagnosis.put("diagnosisName", "");
			diagnosis.put("diagnosisType", "");			
		}*/
		PageData heightData = 
				(PageData) dao.findForObject("PatientMapper.getHeight", pd);
		String height ="0";
		if(heightData != null){
			height = heightData.get("height").toString();	
		}
		String weight= "0";
		String waist = "0";
		PageData bodyData = 
				(PageData) dao.findForObject("PatientMapper.getBodyData", pd);
		if(bodyData != null){
			if(bodyData.get("weight") != null){
				weight = bodyData.get("weight").toString();				
			}
			if(bodyData.get("waist") != null){
				/*double waistDouble = (double) bodyData.get("waist");
				int waistInt = (int)waistDouble;
				waist = String.valueOf(waistInt);*/
				waist = bodyData.get("waist").toString();
			}
		}	
		String level = "1";
		if(!"0".equals(height) && !"0".equals(weight)){
			double heightDouble = Double.parseDouble(height);
			height = String.valueOf((int)(heightDouble*100));
			double weightDouble = Double.parseDouble(weight);
			double bmi = weightDouble/(heightDouble*heightDouble);
			if(25<=bmi&&bmi<=28){
				level = "2";				
			}else if(bmi>28){
				level = "3";
			}
		}
		result.put("level", level);
		result.put("height", height);
		result.put("weight", weight);
		result.put("waist", waist);
		result.put("userId", pd.get("userId").toString());
		//根据userId查询化验单表，并返回化验单集合
		List<PageData> reportUrlList = 
				(List<PageData>) dao.findForList("PatientMapper.getReportUrlList", pd);
		result.put("reportUrlList", reportUrlList);		
		//将身高，体重，腰围，CAP更新到患者病例中
		/*pd.put("height", height);
		pd.put("weight", weight);
		pd.put("waist", waist);
		pd.put("CAP", CAP);
		dao.update("PatientMapper.updatePatientCase", pd);		*/
		return result;
	}

	public List<PageData> getCaloryOfWeek(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//根据userId查询uerName
		String userName = 
				(String) dao.findForObject("PatientMapper.getUserName", pd);
		
		pd.put("userName", userName);
		//去gameMessage表查最近一周的实际完成的热量，截止日期到今天，即调接口的时间
		List<PageData> list = new ArrayList<PageData>();
		Date nowTime = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(nowTime);
		//查询一周热量
		Date temp;
		PageData appleCaloryParam = new PageData();
		appleCaloryParam.put("userId", pd.get("userId"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(int i=0;i<7;i++){
			temp = calendar.getTime();
			String date = sdf.format(temp);
			pd.put("date", date);
			//查询数据.challenge表查询数据
			PageData calory = 
					(PageData) dao.findForObject("PatientMapper.getCalory", pd);
			if(calory !=null && calory.get("calory") != null){
					double caloryData =  (double) calory.get("calory");
					calory.put("calory", (int)caloryData);
					list.add(calory);					
			}else{
				//appleCalory表查询数据
				appleCaloryParam.put("date", date);
				PageData appleCalory = 
						(PageData) dao.findForObject("PatientMapper.findAppleCalory", appleCaloryParam);
				if(appleCalory != null && appleCalory.get("calory") != null){
					list.add(appleCalory);					
				}else{
					PageData caloryTemp = new PageData();
					caloryTemp.put("calory", "0");
					caloryTemp.put("date", temp.getTime());
					list.add(caloryTemp);
				}
			}
			//日期减一天
			calendar.add(Calendar.DATE, -1);			
		}		
		return list;
	}

	/*public PageData saveTestReport(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException {
		// TODO Auto-generated method stub
		return ImageUpLoader.saveTestReport(request,dao);
	}*/

	public PageData getAddressPartmentAndProfessionName() throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		// TODO Auto-generated method stub
		List<PageData> provinceList = (List<PageData>) dao.findForList("PatientMapper.getProvinceList", null);
		//遍历省份集合，得到省份和id，
		for(int i = 0;i<provinceList.size();i++){
			//根据id去city表查询城市集合
			List<PageData> cityList = (List<PageData>) dao.findForList("PatientMapper.getCityList", provinceList.get(i));
			provinceList.get(i).put("city", cityList);
			provinceList.get(i).remove("id");
			//遍历city集合，得到city和city id
			for(int j=0;j<cityList.size();j++){
				cityList.get(j).put("name", cityList.get(j).get("city"));
				cityList.get(j).remove("city");
				//根据cityId查询 district 表
				List<PageData> district = (List<PageData>) dao.findForList("PatientMapper.getDistrictList", cityList.get(j));
				cityList.get(j).put("area", district);
				cityList.get(j).remove("id");
			}
		}
		List<PageData> departMentList = getDepartMentList(null);
		List<PageData> professionNameList = getProfessionNameList(null);
		result.put("addressList", provinceList);
		result.put("departmentList", departMentList);
		result.put("professionNameList", professionNameList);		
		return result;
	}

	public void deleteDiagnosis(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.delete("PatientMapper.deleteDiagnosis", pd);
	}

	public void modifyReprotTime(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		String date = pd.getString("date");
		Long modifyTime = Long.parseLong(date);
		pd.put("date", new Date(modifyTime));
		dao.update("PatientMapper.modifyReprotTime", pd);
	}

	public void deleteTestReport(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.delete("PatientMapper.deleteTestReport", pd);
	}

	public PageData saveTestReport(PageData pd) {
		// TODO Auto-generated method stub
		return ImageUpLoader.saveTestReport(pd,dao);
	}

	public PageData getPatientMessageChanged(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		result.put("ifChanged", false);
		List<PageData> messageChanged = 
				(List<PageData>) dao.findForList("PatientMapper.getPatientMessageChanged", pd);
		if(messageChanged != null && messageChanged.size()>0){
			result.put("ifChanged", true);
		}
		return result;
	}

	public void saveUserDefinedDiagnosisType(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		//根据uesrId查询患者自定义病症表里是否有该病症，如果有，则不操作，如果没有，则添加
				PageData diagnosis = 
						(PageData) dao.findForObject("PatientMapper.findPatieintDefinedDiagnosis", pd);
				if(diagnosis != null){
					return;
				}else{
					//添加数据
					dao.save("PatientMapper.addPatientDefinedDiagnosis", pd);					
				}
				
	}

	public void deleteUserDefinedDiagnosis(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.delete("PatientMapper.deleteUserDefinedDiagnosis", pd);
	}

	public PageData savePatientTestReport(HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		return ImageUpLoader.savePatientTestReport(request, dao);		
	}

	public PageData getPeriodTime() throws ParseException {
		// TODO Auto-generated method stub
		Calendar calendar = Calendar.getInstance();
		PageData result = new PageData();
		Date dateFinal = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateFinalString = sdf.format(dateFinal);
		Date dateEnd = sdf.parse(dateFinalString);
		calendar.setTime(dateEnd);
		calendar.add(Calendar.DATE, 1);
		Date dateEndTemp = calendar.getTime();
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		result.put("dateEnd", sdf2.format(dateEndTemp));
		//向前
		calendar.setTime(dateEnd);
		calendar.add(Calendar.DATE, -6);
		Date dateStart = calendar.getTime();
		System.out.println(dateStart +"dateStart");
		result.put("dateStart", sdf2.format(dateStart));		
		return result;
	}

	public void saveCalory(JSONObject param) throws Exception {
		// TODO Auto-generated method stub
		//message表建立患者和医生的对话信息
		JSONObject paramData = param.getJSONObject("param");
		JSONArray caloryList = paramData.getJSONArray("caloryList");
		String userId =  paramData.getString("userId");
		PageData temp = new PageData();
		temp.put("userId", userId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(int i= 0;i<caloryList.size();i++){
			JSONObject objTemp = caloryList.getJSONObject(i);
			String calory = "";
			int caloryData = 0;
			if(objTemp.get("calory") != null && !objTemp.get("calory").equals("")){
				calory  = objTemp.get("calory").toString();	//是步数
				caloryData = (Integer.valueOf(calory))*40/1000;//每步40卡，数据记录的是千卡
				
			}else{
				continue;
			}
			if(objTemp.get("date") == null){
				continue;
			}
			 String	 date =  objTemp.get("date").toString();			
			 Date caloryDate = sdf.parse(date);
			 String caloryDateString = sdf.format(caloryDate);
			 temp.put("calory", caloryData);
			 temp.put("date", caloryDateString);
			 temp.put("dateSave", caloryDate);
			 //第一步，查询当前日期是否已经有数据，若有则更新，若没有则插入
			 PageData caloryInfo = 
					 (PageData) dao.findForObject("PatientMapper.findAppleCalory", temp);
			 if(caloryInfo != null){
				 //执行更新操作
				 dao.update("PatientMapper.updateAppleCalory", temp);
			 }else{
				 // 执行插入操作
				 dao.save("PatientMapper.saveAppleCalory", temp);
			 }
			 
			 
		}
	}

	public PageData getRealReportPicture(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		return (PageData) dao.findForObject("PatientMapper.getRealReportPicture", pd);
	}
	
	
	public PageData getAlertInfo(PageData pd) throws Exception {
		//根据patientId查询是否有新消息，并将新的消息设置为已读
		PageData result = new PageData();
		List<PageData> alertList = 
				(List<PageData>) dao.findForList("PatientMapper.getAlertList", pd);
		if(alertList != null && alertList.size()==0){
			result.put("ifExist", false);
			return result;
		}
		result.put("ifExist", true);		
		//遍历集合，添加信息
		for(int i=0;i<alertList.size();i++){
			String reminderType = alertList.get(i).get("reminderType")+"";
			if("1".equals(reminderType)){
				//提醒人身份为医生，在医生表中查找名字
				String idTemp = alertList.get(i).get("reminderId")+"";
				String name = 
						(String) dao.findForObject("DoctorMapper.getDocName", idTemp);
				alertList.get(i).put("name", name);
				alertList.get(i).remove("reminderId");
				alertList.get(i).remove("reminderType");
			}else{
				//提醒人身份是助手，寻找改助手的名字
				String idTemp = alertList.get(i).get("reminderId")+"";
				String name = 
						(String) dao.findForObject("DoctorMapper.getDoctorNameByAssistantId", idTemp);
				alertList.get(i).put("name", name);
				alertList.get(i).remove("reminderId");
				alertList.get(i).remove("reminderType");				
			}
		}
		//将通知更改为已读
		dao.update("PatientMapper.updateAlertInfo", pd);		
		return result;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
